# -*- coding: UTF-8 -*-
__license__ = "GPL http://www.gnu.org/licenses/gpl.txt"
__author__="xushengs@gmail.com"
__homepage__ = "http://fdream.net"
__date__ ="2010-2-26 17:39:27"
__version = "0.1"

from config import config
from lib.usercookie import usercookie
from lib.gtwtools import gtwtools

import logging
from urllib import quote, urlencode
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
#from google.appengine.api import urlfetch

#from django.utils import simplejson as json

class Home(webapp.RequestHandler):
    def get(self):
        process(self, method='get')
    def post(self):
        process(self, method='post')

# url map of home
#    ?update
#    ?destroy
#    ?retweet
#    ?status
#
def process(handler, method):
    request = handler.request
    response = handler.response;
    #method = m
    
    tokens = None
    if config.cookie_name in request.cookies:
        tokens = usercookie.decrypt(request.cookies[config.cookie_name])

    if tokens is None:
        response.headers['Location'] = '/login/'
        response.set_status(302)
        return
    
    do = request.get('do')
    action_maps = {
        'home': homepage,
        'refresh': refresh,
        # tweet action
        'update': update,
        'retweet': retweet,
        'oldretweet': oldretweet
    }
    if do in action_maps:
        action_maps.get(do)(handler, tokens)
    else:
        homepage(handler, tokens)
    
    return

def oldretweet(handler, tokens):
    #request = handler.request
    #response = handler.response
    #status = request.get('status')
    return

def retweet(handler, tokens):
    #request = handler.request
    #response = handler.response
    #status = request.get('status')
    return
    
def update(handler, tokens):
    request = handler.request
    response = handler.response
    status = request.get('status')
    reply_to = request.get('reply_to')
    
    # TODO: message length limit: 140
    data = {'status': status.encode('UTF-8')}
    data_params = {'status': quote(status.encode('UTF-8'), '~')}
    if reply_to != '':
        data['in_reply_to_status_id'] = reply_to
        data_params['in_reply_to_status_id'] = reply_to
    
    url = config.api + 'statuses/update.' + config.format
    params = gtwtools.get_oauth_params(base_url = url, 
                                       params = {'oauth_token': tokens['oauth_token']}, 
                                       temp_params = data_params, 
                                       token_secret = tokens['oauth_token_secret'], 
                                       method = 'POST')
    result = gtwtools.get_json(url=url, body=urlencode(data), headers={'Authorization': 'OAuth ' + gtwtools.dict2qscomma(params)}, method='POST')
    logging.error('update result: %s \n message: %s \n params: %s' % (result, status, params))
    if result is None:
        response.out.write('Update Status Error')
        return
    
    response.headers['Location'] = '/'
    response.set_status(302)
    return

def refresh(handler, tokens):
    #response = handler.response
    #request = handler.request
    
    return

def homepage(handler, tokens):
    response = handler.response;
    tpl = config.tpl_path + 'home.html'

    # fetch user profile
    url = config.api + 'users/show.' + config.format
    params = gtwtools.get_oauth_params(base_url = url, params = {'oauth_token': tokens['oauth_token']}, temp_params = {'screen_name': tokens['screen_name']}, token_secret = tokens['oauth_token_secret'], method = 'GET')
    user = gtwtools.get_json(url=url + '?screen_name=' + tokens['screen_name'], headers={'Authorization': 'OAuth ' + gtwtools.dict2qscomma(params)}, method='GET')
    if user is None:
        response.out.write('访问Twitter出错，可能是Google App Engine或Twitter出现了问题，请稍后再试。')  
        return
    
    phrase = gtwtools.semantic_time(user['status']['created_at'], '%a %b %d %H:%M:%S +0000 %Y')
    user['status']['time_text'] = phrase

    # fetch home timeline
#    url = config.api + 'statuses/home_timeline.' + config.format
#    params = gtwtools.get_oauth_params(base_url = url, params = {'oauth_token': tokens['oauth_token']}, temp_params = {'count': config.pagesize}, token_secret = tokens['oauth_token_secret'], method = 'GET')
#    tweets = gtwtools.get_json(url=url + '?count=' + str(config.pagesize), headers={'Authorization': 'OAuth ' + gtwtools.dict2qscomma(params)}, method='GET')
#    if tweets is None:
#        response.out.write('访问Twitter出错，可能是Google App Engine或Twitter出现了问题，请稍后再试。')
#        return
#    
#    for tweet in tweets:
#        tweet['time_text'] = gtwtools.semantic_time(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y')
    
#    response.out.write(template.render(tpl, {'user': user, 'tweets': tweets}))
    response.out.write(template.render(tpl, {'user': user}))
        #response.out.write('Welcome!')
